#region (c) 2014 THN Solutions LLC. - All rights reserved
/*
THN MVC MODULE FOR THN WEB SERVER

Copyright (c) 2014, THN Solutions LLC. ( www.ThnSolutions.com )
Author: Nguyễn, M. Hải                 ( www.Minh-Hai.com     )
All rights reserved.

This library is dual-licensed.
  + For use in commercial software, please obtain a commercial license from THN Solutions LLC.    

  + For use in free software, this library is licensed under GPL version 3. A summary of 
	GPLv3 is listed below. You should also find a copy of GPLv3 as file License_GPLv3.txt 
	included with the source-code files.

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License version 3 as published by
    the Free Software Foundation  of the License.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#endregion

#region Record of Change
//             							CHANGE HISTORY
// -------------------------------------------------------------------------------------
// |   DATE    | DEVELOPER  | DESCRIPTION                                              |
// -------------------------------------------------------------------------------------
// | 14-Apr-13 | HaiNM      | First creation.                                          |
// -------------------------------------------------------------------------------------
//
#endregion

#region Record of Audit
//             							REVIEW HISTORY
// -------------------------------------------------------------------------------------
// |   DATE    | REVIEWER   | NOTES                                                    |
// -------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------
//
#endregion

#region Using directives
using Microsoft.CSharp;
using System;
using System.CodeDom.Compiler;
using System.IO;
using System.Reflection;
using System.Web.Razor;
using Thn;
using Thn.Collections;
#endregion

namespace Thn.Web.Razor
{
    /// <summary>
    /// Wrapper around ASP.NET razor template engine.
    /// </summary>
    /// <typeparam name="TTemplate">Type of base view template.</typeparam>
#if DEBUG || TESTING
    public
#else
    public
#endif
 class RazorEngine<TTemplate>
    {
        #region Fields
        #endregion

        #region Properties

        #region Referenced Assemblies
        private List<string> mReferencedAssemblies = new List<string>();
        /// <summary>
        /// Gets or sets list of referenced assemblies.
        /// </summary>
        public List<string> ReferencedAssemblies
        {
            get { return mReferencedAssemblies; }
            set { mReferencedAssemblies = value; }
        }
        #endregion

        #region Referenced Namespaces
        private List<string> mReferencedNamespaces = new List<string>();
        /// <summary>
        /// Gets or sets list of referenced namespaces.
        /// </summary>
        public List<string> ReferencedNamespaces
        {
            get { return mReferencedNamespaces; }
            set { mReferencedNamespaces = value; }
        }
        #endregion

        #endregion

        #region Create Engine
        RazorTemplateEngine CreateEngine(string generatedNamespace, string generatedClass)
        {
            RazorEngineHost host = new RazorEngineHost(new CSharpRazorCodeLanguage());
            host.DefaultBaseClass = typeof(TTemplate).FullName;
            host.DefaultNamespace = generatedNamespace;
            host.DefaultClassName = generatedClass;
            foreach (var item in this.ReferencedNamespaces)
            {
                host.NamespaceImports.Add(item);
            }

            return new RazorTemplateEngine(host);
        }
        #endregion

        #region Get Safe Class Name
        /// <summary>
        /// Returns a unique ClassName for a template to execute
        /// Optionally pass in an objectId on which the code is based
        /// or null to get default behavior.
        /// 
        /// Default implementation just returns Guid as string
        /// </summary>
        string GetSafeClassName(object objectId)
        {
            return "_" + Guid.NewGuid().ToString().Replace("-", "_");
        }
        #endregion

        #region Parse And Compile
        /// <summary>
        /// Parses and compiles a markup template into an assembly and returns
        /// an assembly name. The name is an ID that can be passed to 
        /// ExecuteTemplateByAssembly which picks up a cached instance of the
        /// loaded assembly.
        /// </summary>
        public RazorCompileResults ParseAndCompileTemplate(
                    TextReader templateSourceReader,
                    RazorCompileArgs args)
        {
            RazorCompileResults result = new RazorCompileResults();

            //pre-conditions
            if (string.IsNullOrEmpty(args.GeneratedNamespace))
                args.GeneratedNamespace = "__RazorEngine";
            if (string.IsNullOrEmpty(args.GeneratedClassName))
                args.GeneratedClassName = GetSafeClassName(null);

            #region Use Razor to generate codes from template
            
            //create engine
            var engine = CreateEngine(args.GeneratedNamespace, args.GeneratedClassName);

            //generate template class as CodeDom
            var generatedResults = engine.GenerateCode(templateSourceReader);

            //get generated codes if required
            CSharpCodeProvider codeProvider = new CSharpCodeProvider();
            CodeGeneratorOptions options = new CodeGeneratorOptions();
            if (args.GenerateCodeAsText)
            {
                using (StringWriter writer = new StringWriter())
                {
                    codeProvider.GenerateCodeFromCompileUnit(generatedResults.GeneratedCode, writer, options);
                    result.mGeneratedCodes = writer.ToString();
                }
            }

            #endregion

            #region Compile codes

            CompilerParameters compilerParameters = new CompilerParameters();

            // Standard Assembly References
            compilerParameters.ReferencedAssemblies.Add("System.dll");
            compilerParameters.ReferencedAssemblies.Add("System.Core.dll");// dynamic support! 
            compilerParameters.ReferencedAssemblies.Add("Microsoft.CSharp.dll");   // dynamic support!

            //THN assembly references
            compilerParameters.ReferencedAssemblies.Add("Thn.dll");
            compilerParameters.ReferencedAssemblies.Add("Thn.Web.dll");
            compilerParameters.ReferencedAssemblies.Add("Thn.Web.Mvc.dll");
            
            // Also add the current assembly so RazorTemplateBase is available
            compilerParameters.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().CodeBase.Substring(8));

            //add custom references
            foreach (var item in ReferencedAssemblies)
            {
                compilerParameters.ReferencedAssemblies.Add(item);
            }

            if (args.CompileToMemory)
            {
                #region Compile code to memory
                
                compilerParameters.GenerateInMemory = true;

                #endregion
            }
            else
            {
                #region Compile code to disk

                compilerParameters.GenerateInMemory = false;
                compilerParameters.OutputAssembly = args.OutputAssemblyPath;

                #endregion
            }

            //compile code
            CompilerResults compilerResults = codeProvider.CompileAssemblyFromDom(compilerParameters, generatedResults.GeneratedCode);

            //set result
            result.SetResults(compilerResults);

            if (result.IsSuccessful)
            {
                string fullname = args.GeneratedNamespace + "." + args.GeneratedClassName;
                result.SetCompiledType(fullname);
            }
            #endregion

            return result;
        }
        #endregion

        #region Constructors
        /// <summary>
        /// Create a new instance.
        /// </summary>
        public RazorEngine()
            : base()
        {
            ReferencedNamespaces.Add("System");
            //ReferencedNamespaces.Add("System.Text");
            //ReferencedNamespaces.Add("System.Collections.Generic");
            //ReferencedNamespaces.Add("System.Linq");
            //ReferencedNamespaces.Add("System.IO");

            //THN
            ReferencedNamespaces.Add("Thn");
            ReferencedNamespaces.Add("Thn.Web");
            ReferencedNamespaces.Add("Thn.Web.Mvc");
        }
        #endregion
    }
}
